package com.example.kingdee.jstSync.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONArray;
import com.example.kingdee.KingdeeCreate.dto.CreateInDto;
import com.example.kingdee.KingdeeCreate.impl.CreateSalBillImpl;
import com.example.kingdee.KingdeeCreate.impl.CreateSalOutBillImpl;
import com.example.kingdee.block.JuShuiTanBlock;
import com.example.kingdee.common.StringUtils;
import com.example.kingdee.dto.PurchaseSyncDto;
import com.example.kingdee.dto.SyncDto;
import com.example.kingdee.entity.*;
import com.example.kingdee.exception.ProcedureException;
import com.example.kingdee.jstSync.JstSyncAbstract;
import com.example.kingdee.jstSync.entity.JstResult;
import com.example.kingdee.kingdeeBridge.common.RequestResult;
import com.example.kingdee.kingdeeBridge.dto.BillWriteInDto;
import com.example.kingdee.kingdeeBridge.dto.PushDto;
import com.example.kingdee.kingdeeBridge.entity.SrcBillEntry;
import com.example.kingdee.kingdeeBridge.kingdeeAbs.FolderKingdee;
import com.example.kingdee.kingdeeBridge.kingdeeImpl.impl.SalOutStockImpl;
import com.example.kingdee.mapper.TBxStMapper;
import com.example.kingdee.service.KingdeeService;
import com.example.kingdee.sqlTool.SqlTool;
import com.example.kingdee.sqlTool.sqltoolEnum.FormIdEnum;
import com.example.kingdee.util.JuShuiTanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 聚水潭销售出库同步实现类
 */
@Service
public class JstSalOutSyncImpl extends JstSyncAbstract {

    @Autowired
    private JuShuiTanBlock juShuiTanBlock;
    @Autowired
    private CreateSalOutBillImpl salOutBill;
    @Autowired
    private TBxStMapper tBxStMapper;
    @Autowired
    private KingdeeService kingdeeService;

    @Override
    public int getOrderInfoPage(SyncDto syncDto, PurchaseSyncDto purchaseSyncDtoPage) {
        return JuShuiTanUtil.getOrderInfoPage(purchaseSyncDtoPage, FormIdEnum.salOutQuery, juShuiTanBlock.getAccessToken());
    }

    @Override
    public JstResult selectJstResult(SyncDto syncDto,  PurchaseSyncDto purchaseSyncDto) {
        JstResult jstResult = new JstResult();
        //制定查询状态
        List<String> status = new ArrayList<>();
        status.add("Confirmed");
        //先从聚水潭上查询销售出库
        purchaseSyncDto.setJstFormId(FormIdEnum.salOutQuery.name());
        purchaseSyncDto.setStatusList(status);
        String jstInfoStr = juShuiTanBlock.getJstInfo(purchaseSyncDto);
        //格式化单据
        List<JstSalOut> jstPurchases = JSONArray.parseArray(jstInfoStr, JstSalOut.class);
        jstResult.setJstSalOutList(jstPurchases);
        jstResult.setEndConfirmDate("2025-04-28");
        return jstResult;
    }

    @Override
    public void kingdeeSync(SyncDto syncDto, JstResult jstResult) {
        List<JstSalOut> jstSalOutList = jstResult.getJstSalOutList();
        for (JstSalOut jstSalOut : jstSalOutList) {
            //线上订单号
             String soId = jstSalOut.getSoId();
            //内部单号
            String oId = String.valueOf(jstSalOut.getOId());
            //销售出库单号
            String ioIdStr = String.valueOf(jstSalOut.getIoId());
            //店铺名称
            String shopName = jstSalOut.getShopName();
            boolean before = true;
            if (!StringUtils.isEmpty(jstResult.getEndConfirmDate())){
                //判断审核截止日期
                Date poDate = DateUtil.parse(jstSalOut.getIoDate());
                Date comparePoDate = DateUtil.parse(jstResult.getEndConfirmDate());
                before = comparePoDate.before(poDate);
            }
            //判断该单号是否还有未处理的错误日志
            if (StringUtils.isEmpty(syncDto.getUserName())){
                int isExist = tBxStMapper.isHavaErrorLog(oId);
                if (isExist > 0){
                    continue;
                }
            }
            if (soId != null && soId.startsWith("HC")){//下推销售订单到销售出库
                //构建下推数据
                List<SrcBillEntry> salOutPushList = createSalOutPush(jstSalOut, oId, soId);
                if(salOutPushList.size() != 0){
                    //构建要修改的数据
                    BillWriteInDto billWriteInDto = new BillWriteInDto();
                    billWriteInDto.setBillType("销售出库");
                    billWriteInDto.setSrcBillEntryList(salOutPushList);
                    RequestResult requestResult = new RequestResult();
                    try {
                        requestResult = kingdeeService.billWriteIn(billWriteInDto);
                    }catch (Exception e){
                        SyncLog syncLog = new SyncLog();
                        syncLog.setJstBillno(oId);
                        syncLog.setSyncErrorMsg(e.getMessage());
                        insertSyncLog(syncDto, syncLog, false);
                    }

                    if (requestResult.getCode().equals("200")){
                        SyncLog syncLog = new SyncLog();
                        syncLog.setJstBillno(oId);
                        syncLog.setKingdeeBillno(requestResult.getNumber());
                        syncLog.setObjectId(requestResult.getId());
                        insertSyncLog(syncDto, syncLog, true);
                    }else {
                        SyncLog syncLog = new SyncLog();
                        syncLog.setJstBillno(oId);
                        syncLog.setSyncErrorMsg(requestResult.getMsg());
                        insertSyncLog(syncDto, syncLog, false);
                    }
                }
            }else {//直接生成销售出库单
                createSalOut(jstSalOut, oId, before, shopName, syncDto);
            }

        }
    }

    //构建下推数据
    public List<SrcBillEntry> createSalOutPush(JstSalOut jstSalOut, String ioIdStr, String soId){
        List<SrcBillEntry> result = new ArrayList<>();
        List<JstSalOut.ItemsBean> itemsList = jstSalOut.getItems();
        for (JstSalOut.ItemsBean itemsBean : itemsList) {
            if (itemsBean.getSkuId().equals("freight")){
                //排除特殊物料
                continue;
            }
            //判断单号是否同步过
            int isExist = tBxStMapper.salOutOrderIsExist(ioIdStr, itemsBean.getSkuId());
            if (isExist == 0){
                //查询销售订单明细行id
                Map<String, Object> salEntryId = tBxStMapper.getSalEntryId(soId, itemsBean.getSkuId());
                double noOutQty = Double.parseDouble(salEntryId.get("noOutQty").toString());
                String entryId = salEntryId.get("entryId").toString();
                //比较未送数量和聚水潭出库数量大小
                double allotQty = Math.min(noOutQty, itemsBean.getQty());
                if (allotQty <= 0){
                    //添加错误日志，错误信息为”对应销售订单已无可出库数量“
                    continue;
                }
                SrcBillEntry srcBillEntry = new SrcBillEntry();
                srcBillEntry.setEntryId(entryId);
                srcBillEntry.setQty(noOutQty);
                srcBillEntry.setStockNumber("CK001");
                srcBillEntry.setReserved1(ioIdStr);
                result.add(srcBillEntry);
            }
        }
        return result;
    }

    //构建销售出库下推数据
    public void createSalOut(JstSalOut jstSalOut, String ioIdStr, boolean before, String shopName, SyncDto syncDto){
        List<JstSalOut.ItemsBean> itemsList = jstSalOut.getItems();
        for (JstSalOut.ItemsBean itemsBean : itemsList) {
            //判断单号是否同步过
            int isExist = tBxStMapper.salOutOrderIsExist(ioIdStr, itemsBean.getSkuId());
            if (isExist == 0 && before && jstSalOut.getStatus().equals("Confirmed")){
                //构建数据
                List<JstSalOut.ItemsBean> salOutItems = new ArrayList<>();
                salOutItems.add(itemsBean);
                CreateInDto createInDto = new CreateInDto();
                createInDto.setReserved1(shopName);
                createInDto.setReserved2(SqlTool.getNowForString());
                createInDto.setReserved3(jstSalOut.getRemark());
                createInDto.setSalOutItems(salOutItems);
                //创建订单
                RequestResult result = salOutBill.createSrcBill(createInDto);
                try {
                    if (result.getCode().equals("200")){
                        //审核订单
                        salOutBill.auditTargetBill(result.getNumber());
                    }else {
                        //删除对应单据
                        salOutBill.deleteTargetBill(result.getId());
                    }
                }catch (Exception e){
                    //删除对应单据
                    salOutBill.deleteTargetBill(result.getId());
                }
                if (result.getCode().equals("200")){
                    SyncLog syncLog = new SyncLog();
                    syncLog.setJstBillno(ioIdStr);
                    syncLog.setKingdeeBillno(result.getNumber());
                    syncLog.setObjectId(result.getId());
                    insertSyncLog(syncDto, syncLog, true);
                }else {
                    SyncLog syncLog = new SyncLog();
                    syncLog.setJstBillno(ioIdStr);
                    syncLog.setSyncErrorMsg(result.getMsg());
                    insertSyncLog(syncDto, syncLog, false);
                }
            }
        }
    }

    @Override
    protected void insertSyncLog(SyncDto syncDto, SyncLog syncLog, boolean isSucceed) {
        syncLog.setSyncType("销售出库同步");
        syncLog.setSrcBill("聚水潭销售出库单");
        syncLog.setTarBill("金蝶销售出库单");
        syncLog.setSyncTime(SqlTool.getNowForString());
        syncLog.setSyncUser(syncDto.getUserName() == null ? "系统自动同步" : syncDto.getUserName());
        if (isSucceed){
            syncLog.setSyncResult("同步成功");
            syncLog.setSyncErrorMsg("无");
        }else {
            syncLog.setIsDispose("未处理");
            syncLog.setSyncResult("同步失败");
        }
        tBxStMapper.insertSyncLog(syncLog);
    }
}
